<?php

namespace app\admin\controller;

use app\admin\controller\CommonController;
use think\Validate;
use think\Db;
use app\util\File;
use app\admin\model\SpecialQrcode;
use app\admin\model\Medical;
use app\admin\model\MedicalAddress;
use app\admin\model\Custom;
use app\admin\model\CtmSpecial;
use app\util\Utils;


class SpecialController extends CommonController {
    /*
     * 红包的兑换码列表
     * author xfwed 
     * date 2019.9.17
     */

    public function specialAndRed() {
        $num = input('param.num');
        $ctm_phone = input('param.ctm_phone');
        $perPage = input('param.perPage');
        $page = input('param.page');

        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        if ($num) {
            $where['num'] = $num;
        }
        if ($ctm_phone) {
            $where['phone'] = $ctm_phone;
        }
        $where = isset($where) ? $where : [];
        $list = SpecialQrcode::where($where)->order('id desc')->paginate($perPage);
        return $this->ajaxReturn(0, '查询成功', $list);
    }

    /*
     * 添加99特权卡和红包的兑换码
     * author xfwed 
     * date 2019.9.17
     */

    public function addSpecialAndRed() {
        $rule = [
            'number' => 'require',
            'money' => 'require',
        ];
        $msg = [
            'number.require' => '数量必须',
            'money.require' => '金额必须',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);

        if (!$validate->check($all)) {
            $error = $validate->getError();
            $this->error($error);
        }
        $number = input('param.number');
        $money = input('param.money');

        for ($i = 0; $i < $number; $i++) {
            $num = SpecialQrcode::order('num desc')->field('num')->find();
            if (empty($num)) {
                $num = '100000';
            } else {
                $num = $num['num'] + 1;
            }

            $file = new File();
            $scene = 'num=' . $num;
            $page = 'packageB/pages/nineAndRed/nineAndRed';
            $baseimg = $file->generateXcxPagecode($scene, $page);

            $data['num'] = $num;
            $data['red_money'] = $money;
            $data['img'] = $baseimg;
            $data['add_time'] = date('Y-m-d H:i:s');
            $add = SpecialQrcode::insert($data);
        }

        if ($add) {
            return $this->ajaxReturn(0, '添加成功', null);
        } else {
            return $this->ajaxReturn(0, '添加失败', null);
        }
    }

    /*
     * 修改兑换码红包金额
     * author xfwed 
     * date 2019.9.17
     */

    public function saveRedMoney() {
        $rule = [
            'id' => 'require',
            'money' => 'require',
        ];
        $msg = [
            'id.require' => 'id必须',
            'money.require' => '金额必须',
        ];
        $all = input('param.');
        $validate = new Validate($rule, $msg);

        if (!$validate->check($all)) {
            $error = $validate->getError();
            $this->error($error);
        }
        $id = input('param.id');
        $phone = SpecialQrcode::where('id','=',$id)->value('phone');
        if($phone){
            return $this->ajaxReturn(3, '兑换码已经兑换', null);
        }
        $save = SpecialQrcode::where('id','=',$id)->update(['red_money'=>$all['money']]);
        if ($save) {
            return $this->ajaxReturn(0, '修改成功', null);
        } else {
            return $this->ajaxReturn(0, '修改失败', null);
        }
    }
    
    /*
     * 逆行者列表
     */
    public function medicalData(){
        $perPage = input('param.perPage');
        $page = input('param.page');
        $status = input('param.status');
        $currentcity = input('param.currentcity');
        $phone = input('param.Phone');
        $perPage = isset($perPage) ? $perPage : 10;
        $page = isset($page) ? $page : 1;
        if (isset($status)) {
            $where['m.status'] = $status;
        }
        
        if ($phone) {
            $where['c.custom_phone'] = $phone;
        }
        
        if ($currentcity) {
            $where['a.currentcity'] = ['like','%'.$currentcity.'%'];
        }
        $where['m.type'] = 2;
        $list = Medical::alias('m')
                ->join('medical_address a','a.ctm_id = m.ctm_id','left')
                ->join('custom c','c.id = m.ctm_id','left')
                ->where($where)
                ->order('m.id asc')
                ->field('m.*,c.custom_phone,c.custom_name')
                ->paginate($perPage);

        foreach ($list as $k=>$v){
           $job_img = $v['job_img'];
           $papers_img = $v['papers_img'];
           $card_img = $v['card_img'];
           if($papers_img){
               $job_img = $job_img.','.$papers_img;
           }
           if($card_img){
               $job_img = $job_img.','.$card_img;
           }
           $job_img = explode(",", $job_img); 
           $list[$k]['job_img'] = $job_img;
           //逆行者收货地址
           $nixingzhe = MedicalAddress::where('ctm_id',$v['ctm_id'])->find();
           $list[$k]['niAddress'] = $nixingzhe;
           //邀请者收货地址
           $yaoqingzhe = MedicalAddress::where('ctm_id',$v['invite_id'])->find();
         $list[$k]['yaoAddress'] = $yaoqingzhe;
        }
        return $this->ajaxReturn(0, '查询成功', $list);
    }
    
    /*
     * 逆行者初审
     */
    public function oneAuditMedical(){
        $id = input('param.id');
        $where['type'] = 2;
        $where['id'] = $id;
        $oneauditname = input('param.oneauditname');
        $list = Medical::where($where)->find();
        if(empty($list)){
            return $this->ajaxReturn(3, 'id有误', null);
        }
        //改审核结果
        $medicalResult = Medical::where('id',$id)->update(['status'=>2,'audit_time'=>date('Y-m-d H:i:s'),'oneauditname'=>$oneauditname]);

        if ($medicalResult) {
            return $this->ajaxReturn(0, '初审通过', null);
        } else {
            return $this->ajaxReturn(40006, '初审失败', null);
        }  
    }
    
    /*
     * 逆行者复审
     */
    public function auditMedical(){
        $id = input('param.id');
        $twoauditname = input('param.twoauditname');
        $where['type'] = 2;
        $where['id'] = $id;
        $list = Medical::where($where)->find();
        if(empty($list)){
            return $this->ajaxReturn(3, 'id有误', null);
        }
        Db::startTrans();
        //改审核结果
        $medicalResult = Medical::where('id',$id)->update(['status'=>1,'audit_time'=>date('Y-m-d H:i:s'),'twoauditname'=>$twoauditname]);
        $ctmRow = Custom::where('id', $list['ctm_id'])->find();
        $ctm_id = $ctmRow['id'];
        //改特权用户
        if ($ctmRow['vip_status'] == 3) {
            $custom_money_result = Custom::where('id', '=', $ctm_id)->update([
                'vip_status' => 2,
            ]);
            //修改客户特权卡
            $ctm_vip_result = CtmSpecial::where('ctm_id', $ctm_id)
                    ->where('type',2)
                    ->order('id desc')
                    ->update([
                'end_time' => date('Y-m-d H:i:s', time() + 86400 * 395),
                'type' => 3,
            ]);
            $code = '0';
            $note = '您已是体验特权，已免费为您升级为正式特权';
        }elseif ($ctmRow['vip_status'] == 2) {
            $custom_money_result = 'true';
            $ctm_vip_result = 'true';
            $code = '0';
            $note = '您已经是特权用户，不需要开通';
        }else {
            $custom_money_result = Custom::where('id', '=', $ctm_id)->update([
                'vip_status' => 2,
            ]);
            //写入或客户特权卡
            $ctm_vip_result = CtmSpecial::insert([
                        'ctm_id' => $ctm_id,
                        'end_time' => date('Y-m-d H:i:s', time() + 86400 * 395),
                        'add_time' => date('Y-m-d H:i:s'),
                        'type' => 3,
            ]);
            $code = '0';
            $note = '开通成功';
        }
        
        if ($medicalResult && $custom_money_result && $ctm_vip_result) {
            Db::commit();
            //发送短信
            $content = "您好！您的逆行者身份已审核通过！打开DAVIDKKM小程序活动页面了解详情，欢迎到您身边的DAVIDKKM门店享受美容服务。";
            $telephone = Custom::where('id', $list['ctm_id'])->value('custom_phone');
            $sendResult = Utils::sendSms($telephone, $content);
            
            if($list['invite_id']){
                $content1 = "您好！您所寻找的逆行者已通过身份审核！您的爱心礼包近期将为您邮寄，请注意查收，欢迎到您身边的DAVIDKKM门店享受美容服务。";
                $telephone1 = Custom::where('id', $list['invite_id'])->value('custom_phone');
                $sendResult = Utils::sendSms($telephone1, $content1);
            }
            return $this->ajaxReturn($code, $note, null);
        } else {
            Db::rollback();
            return $this->ajaxReturn(40006, '开通失败', null);
        }  
    }
    
    /*
     * 逆行者审核失败
     */
    public function auditFailMedical(){
        $id = input('param.id');
        $why = input('param.why');
        $failauditname = input('param.failauditname');
        $where['type'] = 2;
        $where['id'] = $id;
        $list = Medical::where($where)->find();
        if(empty($list)){
            return $this->ajaxReturn(3, 'id有误', null);
        }
        //改审核结果
        $medicalResult = Medical::where('id',$id)
                ->update(['status'=>3,'why'=>$why,'audit_time'=>date('Y-m-d H:i:s'),'failauditname'=>$failauditname]);

        if ($medicalResult) {
            return $this->ajaxReturn(0, '操作成功', null);
        } else {
            return $this->ajaxReturn(40006, '操作失败', null);
        }  
    }
    
    

}
